﻿using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using HtmlAgilityPack;
using SC2TV.Object;
using SC2TV.Tools;

namespace SC2TV.ViewModel
{
    public class PrivateMessageReaderViewModel : BaseViewModel
    {
        private string participants;

        public PrivateMessageReaderViewModel()
        {
            Messages = new ObservableCollection<PrivateMessagePart>();
        }

        public string Participants
        {
            get { return participants; }
            set { participants = value; OnPropertyChanged(); }
        }

        public ObservableCollection<PrivateMessagePart> Messages { get; set; } 

        public string Token;

        public async Task Load(string messageUrl)
        {
            try
            {
                var requester = new Requester(messageUrl);
                var response = await requester.Get();
                var html = new HtmlDocument();
                html.LoadHtml(response.Html);
                var htmlMessages = html.DocumentNode.SelectNodes("//*[@id=\"content\"]/div[1]/div[2]/div");
                foreach (var participant in htmlMessages[0].SelectNodes("a"))
                {
                    Participants += participant.InnerText + ", ";
                }
                for (var i = 1; i < htmlMessages.Count-1; i++)
                {
                    var temp = new PrivateMessagePart
                    {
                        User = htmlMessages[i].SelectSingleNode("div[2]/div[1]/span[1]").InnerText,
                        Message = htmlMessages[i].SelectSingleNode("div[2]/div[2]/p").InnerText,
                        MessageDate = htmlMessages[i].SelectSingleNode("div[2]/div[1]/span[2]").InnerText
                    };
                    Messages.Add(temp);
                }
                
                Token = htmlMessages[htmlMessages.Count-1].SelectSingleNode("input[2]").GetAttributeValue("value", "");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }
    }
}
